package net.bxx2004.extand.events;

import net.bxx2004.extand.extand;
import net.bxx2004.extand.manager.ConfigManager;
import net.bxx2004.extand.util.JDBCUtil;
import net.bxx2004.extand.util.Logger;
import net.bxx2004.extand.values.Value;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static org.bukkit.Bukkit.getServer;

public class PlayerChat implements Listener {
    @EventHandler
    public void onChat(AsyncPlayerChatEvent event){
        try {
            if (Value.map.containsKey(event.getPlayer()) && Value.map.get(event.getPlayer()) == null){
                event.setCancelled(true);
                Player player = event.getPlayer();
                if (!event.getMessage().equalsIgnoreCase("cancel")){
                    switch (ConfigManager.getSetting().getString("Storge.Type")){
                        case "Yaml":
                            a(player, event.getMessage());
                            break;
                        case "MySql":
                            String message = event.getMessage();
                            if (message.contains("http://")){
                                message = message.replaceAll("/", "").replaceAll("http:", "");
                            }
                            String sql = "SELECT Code FROM " + ConfigManager.getSetting().getString("Storge.SqlTablename");
                            Connection conn = JDBCUtil.getConnection();
                            Statement st = conn.createStatement();
                            ResultSet resultSet = st.executeQuery(sql);
                            List<String> codes = new ArrayList<>();
                            while (resultSet.next()){
                                codes.add(resultSet.getString(1));
                            }
                            for (String s : codes){
                                System.out.println(s);
                            }
                            JDBCUtil.close(resultSet, st, null, null);
                            if (codes.contains(message)){
                                String sql1 = "select * from " + ConfigManager.getSetting().getString("Storge.SqlTablename") + " where PlayerName='"+ player.getName() +"'";
                                PreparedStatement pst = conn.prepareStatement(sql1);
                                ResultSet rs  = pst.executeQuery();
                                String meCode = null;
                                while(rs.next()){
                                    meCode = rs.getString("Code");
                                }
                                JDBCUtil.close(rs, null, null, pst);
                                if (message.equalsIgnoreCase(meCode)){
                                    player.sendMessage(ConfigManager.getSetting().getString("Message.MeExtand"));
                                }else {
                                    String sql2 = "select * from " + ConfigManager.getSetting().getString("Storge.SqlTablename") + " where Code='"+ message +"'";
                                    PreparedStatement pst1 = conn.prepareStatement(sql2);
                                    ResultSet rs1  = pst1.executeQuery();
                                    String BackPlayer = null;
                                    int Amount = 0;
                                    while(rs1.next()){
                                        BackPlayer = rs1.getString("PlayerName");
                                        Amount = rs1.getInt("Amount");
                                    }
                                    JDBCUtil.close(rs1, null, null, pst1);
                                    String sql3 = "UPDATE "+ ConfigManager.getSetting().getString("Storge.SqlTablename") +" SET Amount='"+ (Amount+1) +"' WHERE Code='"+ message +"'";
                                    PreparedStatement pst2 = conn.prepareStatement(sql3);
                                    pst2.execute();
                                    JDBCUtil.close(null, null, null, pst2);
                                    String sql4 = "UPDATE "+ ConfigManager.getSetting().getString("Storge.SqlTablename") +" SET BackPlayer='"+ BackPlayer +"' WHERE PlayerName='"+ player.getName() +"'";
                                    PreparedStatement pst3 = conn.prepareStatement(sql4);
                                    pst3.execute();
                                    JDBCUtil.close(null, null, null, pst3);
                                    player.sendMessage(ConfigManager.getSetting().getString("Message.SuccessExtand").replaceAll("%Player_Back%", BackPlayer));
                                    try {
                                        for (String s:ConfigManager.getSetting().getStringList("Commands")) {
                                            getServer().dispatchCommand(Bukkit.getConsoleSender(), s.replaceAll("%Player_Back%", BackPlayer).replaceAll("%Player%", player.getName()));
                                        }
                                    }catch (Exception e){}
                                    if (ConfigManager.getSetting().getBoolean("Log")){
                                        Logger.log(event.getPlayer().getName() + "成功的被" + BackPlayer + "邀请到了游戏.");
                                    }
                                    Value.map.remove(player);
                                    JDBCUtil.close(null, null, conn, null);
                                }
                            }else {
                                JDBCUtil.close(null, null, conn, null);
                                player.sendMessage(ConfigManager.getSetting().getString("Message.FailExtand"));
                            }
                            break;
                        default:
                            a(player, event.getMessage());
                            break;
                    }
                }else {
                    player.sendMessage(ConfigManager.getSetting().getString("Message.CancelInput"));
                    Value.map.remove(player);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void a(Player player, String message){
        if (message.contains("http://")){
            message = message.replaceAll("/", "").replaceAll("http:", "");
        }
        Iterator iterator = ConfigManager.getConfig().getKeys(false).iterator();
        Iterator iterator1 = ConfigManager.getConfig().getKeys(false).iterator();
        List<String> LIST = new ArrayList<String>();
        while (iterator1.hasNext()){
            LIST.clear();
            String s = (String) iterator1.next();
            LIST.add(ConfigManager.getConfig().getString(s + ".Code"));
        }
        if (!LIST.contains(message)){
            player.sendMessage(ConfigManager.getSetting().getString("Message.FailExtand"));
        }else if (ConfigManager.getConfig().getString(player.getName() + ".Code").equalsIgnoreCase(message)){
            player.sendMessage(ConfigManager.getSetting().getString("Message.MeExtand"));
        }
        while (iterator.hasNext()){
            String Name = (String) iterator.next();
            if (ConfigManager.getConfig().getString(Name + ".Code").equalsIgnoreCase(message) && !ConfigManager.getConfig().getString(player.getName() + ".Code").equalsIgnoreCase(message)){
                ConfigManager.getConfig().set(Name + ".Amount", ConfigManager.getConfig().getInt(Name + ".Aumount") + 1);
                ConfigManager.getConfig().set(player.getName() + ".BackPlayer" , Name);
                extand.getPlugin(extand.class).saveConfig();
                player.sendMessage(ConfigManager.getSetting().getString("Message.SuccessExtand").replaceAll("%Player_Back%", Name));
                try {
                    for (String s:ConfigManager.getSetting().getStringList("Commands")) {
                        getServer().dispatchCommand(Bukkit.getConsoleSender(), s.replaceAll("%Player_Back%", Name).replaceAll("%Player%", player.getName()));
                    }
                }catch (Exception e){}
                if (ConfigManager.getSetting().getBoolean("Log")){
                    Logger.log(player.getName() + "成功的被" + Name + "邀请到了游戏.");
                }
                Value.map.remove(player);
                break;
            }
        }
    }
}
